package com.shujia.spark.stream

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.streaming.{Durations, StreamingContext}
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}

object Demo6Submit {
  def main(args: Array[String]): Unit = {
    //创建spark环境
    val conf = new SparkConf()
    conf.setAppName("state")

    //去掉master
    //conf.setMaster("local[2]")
    val sc = new SparkContext(conf)

    val ssc = new StreamingContext(sc, Durations.seconds(5))

    //改成hdfs的路径
    ssc.checkpoint("/data/checkpoint")

    //读取数据
    val linesDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)


    /**
     * 统计总的单词的数量
     */
    val kvDS: DStream[(String, Int)] = linesDS
      .flatMap(line => line.split(","))
      .map(word => (word, 1))

    //累加统计单词的数量
    val countDS: DStream[(String, Int)] = kvDS
      .updateStateByKey((seq: Seq[Int], state: Option[Int]) => Option(seq.sum + state.getOrElse(0)))


    //整理数据
    val resultDS: DStream[String] = countDS.map {
      case (word: String, count: Int) =>
        s"$word\t$count"
    }

    //将统计结果保存到文件
    resultDS.saveAsTextFiles("/data/stream_count")

    ssc.start()
    ssc.awaitTermination()
    ssc.stop()

  }
}
